package com.msunsoft.system.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.msunsoft.common.BaseService;
import com.msunsoft.exception.BusinessException;
import com.msunsoft.support.dozer.DozerMapperHelper;
import com.msunsoft.system.mybatis.dao.SysOfficeMapper;
import com.msunsoft.system.mybatis.model.SysOffice;
import com.msunsoft.system.vo.OfficeTreeVo;

@Service
public class OfficeService extends BaseService<SysOfficeMapper, SysOffice> {

    public List<OfficeTreeVo> selectTreeByType(Integer officeType) {
        List<SysOffice> list = this.dao.selectAllByType(officeType);
        List<OfficeTreeVo> voList = new ArrayList();

        // Map<String, Dict> map = this.dictService.selectByType("sys_office_type");

        for (SysOffice office : list) {
            OfficeTreeVo officeVo = DozerMapperHelper.map(office, OfficeTreeVo.class);
            // String type = officeVo.getType();
            // Dict dict = map.get(type);
            // officeVo.setTypeName(dict.getLabel());

            //            Area area = this.areaService.selectById(office.getAreaId());
            //            if (area != null) {
            //                officeVo.setAreaName(area.getName());
            //            }

            officeVo.setText(officeVo.getName());
            voList.add(officeVo);

        }

        return genTree(voList);
    }

    private List<OfficeTreeVo> genTree(List<OfficeTreeVo> voList){
        return voList;
    }

    public Integer deleteById4Tree(Integer id) {
        Integer count = this.dao.selectCountChildById(id);
        if (count != 0) {
            throw new BusinessException("非法操作!该节点下存在子节点,请先删除子节点!");
        }
        return super.deleteById (id);
    }

    /**
     * 查询所有机构
     * @return
     */
    // TODO 需引入缓存
    public Map<Integer, SysOffice> selectAll() {
        List<SysOffice> list = this.dao.selectAllByType(null);
        Map<Integer, SysOffice> map = new HashMap();
        for (SysOffice office : list) {
            map.put(office.getId(), office);
        }
        return map;
    }
}
